
class Admin::SalesPromotionsController < Admin::BaseController
  before_action :set_promotion, only: [:show, :edit, :update, :destroy, :enable_or_disable]

  def index
    @sales_promotions = SalesPromotion.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order("id desc")
  end

  def show
    respond_to do |format|
      format.html
      format.json { render json: {status: 'ok', promotion: @sales_promotions}}
    end
  end

  def new
    @sales_promotion = SalesPromotion.new
  end

  def edit
    render action: :new
  end

  def create
    promotion_params[:started_at] = Date.parse(promotion_params[:started_at])
    promotion_params[:ended_at] = Date.parse(promotion_params[:ended_at])
    promotion_params[:main_img] = get_first_img(promotion_params)

    if SalesPromotion.create(promotion_params)
      flash[:notice] = "新建活动成功"
      redirect_to admin_sales_promotions_path
    else
      flash[:notice] = "新建活动失败"
      render action: :new
    end
  end

  def update
    promotion_params[:started_at] = Date.parse(promotion_params[:started_at])
    promotion_params[:ended_at] = Date.parse(promotion_params[:ended_at])
    promotion_params[:main_img] = get_first_img(promotion_params)

    @sales_promotion.attributes = promotion_params
    if @sales_promotion.save
      flash[:notice] = "修改活动成功"
      redirect_to admin_sales_promotions_path
    else
      flash[:notice] = "修改活动失败"
      render action: :new
    end
  end

  def destroy
  end

  def enable_or_disable
    begin
      if @sales_promotion.actived
        @sales_promotion.actived = false
      else
        @sales_promotion.actived = true
      end
      @sales_promotion.save!
      flash[:notice] = "修改活动状态成功"
      redirect_to admin_sales_promotions_path
    rescue
      flash[:notice] = "修改活动状态失败"
      redirect_to :back
    end
  end

  private

  def set_promotion
    @sales_promotion = SalesPromotion.find(params[:id])
  end

  def promotion_params
    params.require(:sales_promotion).permit!
  end
end
